<template>
  <doc-alert title="【交易】交易订单" url="https://doc.iocoder.cn/mall/trade-order/" />
  <doc-alert title="【交易】购物车" url="https://doc.iocoder.cn/mall/trade-cart/" />

  <ContentWrap>
    <el-form
      v-hasRole="['shop_admin']"
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item v-show="false" label="hideId">
        <el-input v-model="formData.id" />
      </el-form-item>
      <el-tabs>
        <el-tab-pane label="售前">
          <el-form-item label="常用备注" prop="popularRemarks">
            <el-select
              v-model="formData.popularRemarks"
              allow-create
              filterable
              multiple
              default-first-option
              :reserve-keyword="false"
              placeholder="请输入或选择常用备注"
            >
              <el-option
                v-for="remark in formData.popularRemarks"
                :key="remark"
                :label="remark"
                :value="remark"
              />
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="配送">
          <el-form-item label="启用包邮" prop="deliveryExpressFreeEnabled">
            <el-switch v-model="formData.deliveryExpressFreeEnabled" class="select-none" />
            <el-text class="w-full" size="small" type="info"> 商城是否启用全场包邮</el-text>
          </el-form-item>
          <el-form-item label="满额包邮" prop="deliveryExpressFreePrice">
            <el-input-number
              v-model="formData.deliveryExpressFreePrice"
              :min="0"
              :precision="2"
              class="!w-xs"
              placeholder="请输入满额包邮"
            />
            <el-text class="w-full" size="small" type="info">
              商城产品满多少金额即可包邮，单位：元
            </el-text>
          </el-form-item>
          <el-form-item label="启用到店自提" prop="deliveryPickUpEnabled">
            <el-switch v-model="formData.deliveryPickUpEnabled" class="select-none" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="售后">
          <el-form-item label="退款理由" prop="afterSaleRefundReasons">
            <el-select
              v-model="formData.afterSaleRefundReasons"
              allow-create
              filterable
              multiple
              default-first-option
              :reserve-keyword="false"
              placeholder="请输入或选择退款理由"
            >
              <el-option
                v-for="reason in formData.afterSaleRefundReasons"
                :key="reason"
                :label="reason"
                :value="reason"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="退货理由" prop="afterSaleReturnReasons">
            <el-select
              v-model="formData.afterSaleReturnReasons"
              allow-create
              filterable
              multiple
              default-first-option
              :reserve-keyword="false"
              placeholder="请输入或选择退货理由"
            >
              <el-option
                v-for="reason in formData.afterSaleReturnReasons"
                :key="reason"
                :label="reason"
                :value="reason"
              />
            </el-select>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      <!-- 保存 -->
      <el-form-item>
        <el-button :loading="formLoading" type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
    <div v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']">
      超管角色，查看配置；列表
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>
import * as ConfigApi from '@/api/mall/trade/config'
import { fenToYuan, yuanToFen } from '@/utils'
import { cloneDeep } from 'lodash-es'

defineOptions({ name: 'TradeConfig' })

const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref()
const formData = ref<any>({
  id: null,
  popularRemarks: [],
  afterSaleRefundReasons: [],
  afterSaleReturnReasons: [],
  deliveryExpressFreeEnabled: false,
  deliveryExpressFreePrice: 0,
  deliveryPickUpEnabled: false
})
const formRules = reactive({
  deliveryExpressFreePrice: [{ required: true, message: '满额包邮不能为空', trigger: 'blur' }]
})

const submitForm = async () => {
  if (formLoading.value) return
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = cloneDeep(unref(formData.value)) as unknown as ConfigApi.ConfigVO
    // 金额放大
    data.deliveryExpressFreePrice = yuanToFen(data.deliveryExpressFreePrice)
    await ConfigApi.saveTradeConfig(data)
    message.success('保存成功')
  } finally {
    formLoading.value = false
  }
}

/** 查询交易中心配置 */
const getConfig = async () => {
  formLoading.value = true
  try {
    const data = await ConfigApi.getTradeConfig()
    if (data != null) {
      formData.value = data
      // 金额缩小
      formData.value.deliveryExpressFreePrice = fenToYuan(data.deliveryExpressFreePrice)
    }
  } finally {
    formLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getConfig()
})
</script>
